import { _decorator, Component, find, instantiate, Node, Prefab, tween, Vec3 ,Animation, v3, isValid, AnimationClip} from 'cc';
import ResManager from './ResManager';
const { ccclass, property } = _decorator;

export enum EffectEnum {
    Baozha = 'effect/Baozha',
    PuTongBaoZha = 'effect/PuTongBaoZha',
    Fire = 'effect/Fire',
    BigFire = 'effect/BigFire',
    Shangdian = 'effect/Shangdian',
    Water = 'effect/Water',
    Bingbao = 'effect/Bingbao',
    YunChen = 'effect/YunChen',
    GeDang = 'effect/GeDang',
    HongDun = 'effect/HongDun',
    Dead = 'effect/Dead',
    ZhongDu = 'effect/ZhongDu',
    HongYu = 'effect/HongYu',
    Guard = 'effect/Guard',
    ClickGround = 'effect/ClickGround',
}

@ccclass('EffectManager')
export class EffectManager extends Component{
    private static _instance;

    static get instance(): EffectManager {
        if (this._instance == null) {
            this._instance = new EffectManager();
        }
        return this._instance
    }


    async play(url:string, position:Vec3):Promise<Node>{
        let prefab = await ResManager.instance.loadAssetByUrl<Prefab>(url)
        let node = instantiate(prefab)
        find('Canvas').addChild(node)
        node.worldPosition = position
        return node
    }


    async playOnce(url:string, position:Vec3,delay:number = 0){
        let prefab = await ResManager.instance.loadAssetByUrl<Prefab>(url)
        await new Promise((resolve) => {
            this.scheduleOnce(() => {
                resolve(1)
            }, delay)
        })
        let node = instantiate(prefab)

        let ani = node.getComponent(Animation)
        ani.defaultClip.wrapMode = AnimationClip.WrapMode.Normal


        find('Canvas').addChild(node)
        node.worldPosition = position

        
        ani.play()
        ani.on(Animation.EventType.FINISHED, () => {
         
            node.destroy()
        }, this);
    }

    async playShoot(url:string, start:Vec3, end:Vec3, time:number,){
        let prefab = await ResManager.instance.loadAssetByUrl<Prefab>(url)
        let node = instantiate(prefab)
        find('Canvas').addChild(node)
        node.worldPosition = start


        let dir = v3(0, 0, 0)
        dir = Vec3.subtract(dir, end, start)
      
        let hu = Math.atan2(dir.y, dir.x)
        // 角度= 弧度 * 180 / pi
        // 弧度= 角度 / 180 * pi
        let angle = hu * 180 / Math.PI
        node.eulerAngles = v3(0, 0, angle)

        tween(node)
        .to(time, { worldPosition:end },{
            onComplete(){
                node.destroy()
            }
        })
        .start()
    }
}


